package com.template.api.service.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.template.api.entity.po.ConfigBanner;
import com.template.api.entity.vo.ParamConfigBannerVO;
import com.template.api.mapper.ConfigBannerMapper;
import com.template.common.constant.CommonPage;
import com.template.common.constant.ConstantPool;
import com.template.common.enums.SysStatusEnum;
import com.template.common.utils.RedisUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author mltong
 */
@Service
public class ManConfigBannerService extends ServiceImpl<ConfigBannerMapper, ConfigBanner> {

    @Resource
    private RedisUtil redisUtil;

    public CommonPage<ConfigBanner> listBanner(ParamConfigBannerVO param) {
        LambdaQueryWrapper<ConfigBanner> queryWrapper = new LambdaQueryWrapper<ConfigBanner>()
                .eq(StringUtils.isNotEmpty(param.getDataGroup()), ConfigBanner::getDataGroup, param.getDataGroup())
                .eq(StringUtils.isNotEmpty(param.getScope()), ConfigBanner::getScope, param.getScope())
                .eq(Objects.nonNull(param.getStatus()), ConfigBanner::getStatus, param.getStatus())
                .orderByAsc(ConfigBanner::getSort);
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<ConfigBanner> configBanners = list(queryWrapper);
        return CommonPage.restPage(configBanners);
    }
    public ConfigBanner getBanner(Integer id) {
        return getById(id);
    }
    public void addBanner(ConfigBanner param) {
        save(param);
        // 清空缓存
        clearBannerCache(param.getScope());
    }
    public void editBanner(ConfigBanner param) {
        updateById(param);
        // 清空缓存
        clearBannerCache(param.getScope());
    }
    public void deleteBanner(Integer id) {
        ConfigBanner configBanner = getBanner(id);
        if(Objects.nonNull(configBanner)){
            configBanner.setDelStatus(SysStatusEnum.NO.getStatus());
            editBanner(configBanner);
        }
    }

    private void clearBannerCache(String scope) {
        // 清空缓存
        redisUtil.remove(ConstantPool.CACHE_KEY_BANNER + scope);
    }

}
